package com.dm.webCrawler.common.utils.translation;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class ChromeTranslationUtil {
    private static final String port= "http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=${tl}&q=${content}";

    /**
     * 谷歌翻译接口
     * @param tl 翻译语种 简体中文:zh_CN
     * @param content 要翻译的内容
     * @return
     */
    public static String translation(String tl,String content){
        String encodeContent=null;
        try {
            encodeContent=URLEncoder.encode(content,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("内容转换为URL编码失败:"+content);
        }
        HttpResponse repo = HttpRequest.get(port.replace("${tl}", tl).replace("${content}",encodeContent )).timeout(10 * 1000).execute();
        String translationBody=repo.body();
        if(repo.getStatus()==200){
            StringBuffer reStrBf=new StringBuffer();
            JSONObject respoObj = JSONObject.parseObject(translationBody);
            JSONArray sentences = respoObj.getJSONArray("sentences");
            if(sentences!=null && sentences.size()>0){
                for (int x=0;x<sentences.size();x++) {
                    reStrBf.append(sentences.getJSONObject(x).getString("trans"));
                }
            }
            return reStrBf.toString();
        }
        throw new RuntimeException("翻译失败"+translationBody);

    }

}
